package com.micro.service.impl;

import com.micro.client.TrainServiceClient;
import com.micro.client.UserServiceClient;
import com.micro.dto.TrainMealOrderDTO;
import com.micro.dto.TrainMealOrderItemDTO;
import com.micro.entity.TrainMealOrder;
import com.micro.entity.TrainMealOrderItem;
import com.micro.repository.TrainMealOrderRepository;
import com.micro.repository.TrainMealOrderItemRepository;
import com.micro.request.MealOrderRequest;
import com.micro.service.TrainMealOrderService;
import com.micro.service.TrainTicketOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class TrainMealOrderServiceImpl implements TrainMealOrderService {

    @Autowired
    private TrainMealOrderRepository trainMealOrderRepository;
    
    @Autowired
    private TrainMealOrderItemRepository trainMealOrderItemRepository;
    
    @Autowired
    private UserServiceClient userServiceClient;
    
    @Autowired
    private TrainServiceClient trainServiceClient;
    
    @Autowired
    private TrainTicketOrderService trainTicketOrderService;

    @Override
    @Transactional
    public TrainMealOrder createOrder(MealOrderRequest request) {
        // 1. 获取用户信息
        UserServiceClient.UserDTO user = userServiceClient.getUserByUsername(request.getUsername());
        
        // 2. 根据trainTicketOrderId获取火车票订单信息，以获取列车ID和座位信息
        // 从order-service中获取火车票订单详情
        com.micro.entity.TrainTicketOrder ticketOrder = trainTicketOrderService.getOrderById(request.getTrainTicketOrderId());
        if (ticketOrder == null) {
            throw new RuntimeException("火车票订单不存在");
        }
        
        // 3. 创建餐食订单
        TrainMealOrder order = new TrainMealOrder();
        order.setUserId(user.getUserId());
        order.setTrainId(ticketOrder.getTrainId()); // 使用准确的列车ID
        order.setSeatNumber(ticketOrder.getSeatId() != null ? ticketOrder.getSeatId().toString() : "01A"); // 使用准确的座位号
        order.setOrderNumber(generateOrderNumber());
        order.setTotalAmount(request.getTotalPrice());
        order.setStatus(TrainMealOrder.OrderStatus.PAID.getValue());
        order.setCreateTime(LocalDateTime.now());
        order.setPaymentTime(LocalDateTime.now());

        // 4. 保存订单主表
        trainMealOrderRepository.insert(order);

        // 5. 创建并保存订单明细
        for (MealOrderRequest.MealOrderItemRequest itemRequest : request.getItems()) {
            TrainMealOrderItem orderItem = new TrainMealOrderItem();
            orderItem.setOrderId(order.getOrderId());
            orderItem.setMealId(itemRequest.getMealId());
            orderItem.setMealName(itemRequest.getMealName());
            orderItem.setMealType(itemRequest.getMealType());
            orderItem.setPrice(itemRequest.getPrice());
            orderItem.setQuantity(itemRequest.getQuantity());
            orderItem.setSubtotal(itemRequest.getSubtotal());
            
            // 保存订单明细
            trainMealOrderItemRepository.insert(orderItem);
            
            // 添加到订单对象中（用于返回）
            order.addOrderItem(orderItem);
        }

        return order;
    }

    @Override
    public List<TrainMealOrderDTO> getOrdersByUsername(String username) {
        UserServiceClient.UserDTO user = userServiceClient.getUserByUsername(username);
        if (user == null) return new ArrayList<>();
        
        List<TrainMealOrder> orders = trainMealOrderRepository.findByUserIdWithExplicitFields(user.getUserId());
        
        return orders.stream().map(this::toDTO).collect(Collectors.toList());
    }

    @Override
    public List<TrainMealOrder> getUserOrders(Long userId) {
        return trainMealOrderRepository.findByUserId(userId);
    }

    @Override
    public TrainMealOrder getOrderDetails(Long orderId) {
        TrainMealOrder order = trainMealOrderRepository.findOrderDetailsById(orderId);
        if (order != null) {
            // 查询订单明细
            List<TrainMealOrderItem> items = trainMealOrderItemRepository.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<TrainMealOrderItem>()
                    .eq("订单ID", orderId)
            );
            order.setOrderItems(items);
        }
        return order;
    }

    @Override
    @Transactional
    public void updateOrderStatus(Long orderId, String status) {
        TrainMealOrder order = trainMealOrderRepository.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        order.setStatus(status);
        if (TrainMealOrder.OrderStatus.PAID.getValue().equals(status)) {
            order.setPaymentTime(LocalDateTime.now());
        }

        trainMealOrderRepository.updateById(order);
    }

    @Override
    public List<TrainMealOrder> getOrdersByStatus(String status) {
        return trainMealOrderRepository.findByStatus(status);
    }

    @Override
    public List<TrainMealOrder> getOrdersByTrainId(Long trainId) {
        return trainMealOrderRepository.findByTrainId(trainId);
    }

    @Override
    public TrainMealOrder getOrderByOrderNumber(String orderNumber) {
        return trainMealOrderRepository.findByOrderNumber(orderNumber);
    }

    private String generateOrderNumber() {
        return "MEAL" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
    }

    private TrainMealOrderDTO toDTO(TrainMealOrder order) {
        TrainMealOrderDTO dto = new TrainMealOrderDTO();
        dto.setOrderId(order.getOrderId());
        dto.setOrderNumber(order.getOrderNumber());
        dto.setUserId(order.getUserId());
        dto.setTrainId(order.getTrainId());
        dto.setSeatNumber(order.getSeatNumber());
        dto.setTotalAmount(order.getTotalAmount());
        dto.setStatus(order.getStatus());
        dto.setCreateTime(order.getCreateTime());
        dto.setPaymentTime(order.getPaymentTime());
        dto.setRemark(order.getRemark());
        
        // 转换订单明细
        List<TrainMealOrderItemDTO> itemDTOs = order.getOrderItems().stream()
                .map(this::toItemDTO)
                .collect(Collectors.toList());
        dto.setOrderItems(itemDTOs);
        
        return dto;
    }

    private TrainMealOrderItemDTO toItemDTO(TrainMealOrderItem item) {
        TrainMealOrderItemDTO dto = new TrainMealOrderItemDTO();
        dto.setItemId(item.getItemId());
        dto.setMealId(item.getMealId());
        dto.setMealName(item.getMealName());
        dto.setMealType(item.getMealType());
        dto.setPrice(item.getPrice());
        dto.setQuantity(item.getQuantity());
        dto.setSubtotal(item.getSubtotal());
        return dto;
    }
}
